package nancal.mp.mvc.sys


import io.swagger.annotations.ApiOperation
import nancal.mp.db.mongo.entity.log.EmailCodeLog
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.mvc.OpenAction
import nbcp.base.comm.JsonResult
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

/**
 * Created by udi on 17-3-19.
 */
@RestController
@RequestMapping("/open/email")
@OpenAction
class Email_Controller {

    //数据应该放入到数据库中  由不同应用配置
    private val host = "smtp.163.com"
    private val port = "465"
    private val from = "18500560730@163.com"
    private val pwd = "RCHNMWKGWDSZLEXB"
//    private val coding = "UTF-8"

    @ApiOperation(value = "发送邮件")
    @PostMapping("/send")
    fun send(
        title: String,   //邮件标题
        content: String,    //邮件内容
        emails: MutableList<String>    //发送的邮件地址集合
    ): JsonResult {
     
//            Security.addProvider(Provider())
        val SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"
        val props = Properties()
        props["mail.smtp.host"] = host
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY)
        props.setProperty("mail.smtp.socketFactory.fallback", "false")
        props.setProperty("mail.smtp.port", port)
        props.setProperty("mail.smtp.socketFactory.port", port)
        props["mail.smtp.auth"] = "true"
        //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
        val session = Session.getDefaultInstance(props, object : Authenticator() {
            override fun getPasswordAuthentication(): PasswordAuthentication {
                return PasswordAuthentication(from, pwd)
            }
        })

        /**
         * 用session为参数定义消息对象
         */
        val message: Message = MimeMessage(session)
        /**
         * 加载发件人地址
         */
        message.setFrom(InternetAddress(from))
        /**
         * 加载收件人地址
         */
        val sendTo: Array<InternetAddress?> = arrayOfNulls<InternetAddress>(emails.size)
        for (i in emails.indices) {
            sendTo[i] = InternetAddress(emails[i])
        }
        message.setRecipients(Message.RecipientType.TO, sendTo)
        /**
         * 设置在发送给收信人之前给自己（发送方）抄送一份，不然会被当成垃圾邮件，报554错
         */
        message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(from))
        /**
         * 加载标题
         */
        message.setSubject(title)
        //设置邮件消息
        message.setText(content)
        //设置发送的日期
        message.setSentDate(Date())
        //调用Transport的send方法去发送邮件
        Transport.send(message)


        var emailLog = EmailCodeLog();
        emailLog.emails  = emails;
        emailLog.subject = title;
        emailLog.content = content;
        mor.log.emailCodeLog.doInsert(emailLog);
        return JsonResult()
    }
}
